package servlet;

import entity.User;
import exception.DataAccessException;
import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/list")
public class ListServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ListServlet.service()");

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<User> users=new ArrayList<User>();
        try {
            con= JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_user ")
                    .toString();

            ps=con.prepareStatement(sql);

            rs=ps.executeQuery();

            while(rs.next()){
                User user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));

                users.add(user);
            }

            con.commit();

        } catch (Exception e){
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            throw new DataAccessException("数据访问失败",e);
        } finally {
            JdbcUtil.close(con,ps,rs);
        }

        request.setAttribute("users",users);
        // request.getRequestDispatcher("/list.jsp").forward(request,response);

        request.getRequestDispatcher("/jquery/list.jsp").forward(request,response);

    }
}
